package Calculator.Parser.Elements;

import Calculator.Exceptions.UnclosedParenthesisException;
import Calculator.Exceptions.WrongExpressionException;
import Calculator.Parser.InfixParser;
import Calculator.Parser.Utilities;

public class Parenthesis extends Token{
	
	public Parenthesis(String id) {
		this.setId(id);
	}

	@Override
	public void performIteration(InfixParser infixParser) throws UnclosedParenthesisException{
		if (Utilities.LEFT_PARENTHESIS.equals(this.getId())){
			infixParser.getOperatorStack().push(this);
		} else {
			Boolean leftFound = Boolean.FALSE;
			while (!infixParser.getOperatorStack().empty() && !leftFound){
				Token topOperator = infixParser.getOperatorStack().pop();
				if (Utilities.LEFT_PARENTHESIS.equals(topOperator.getId())){
					leftFound = Boolean.TRUE;
				} else {
					infixParser.getOutput().add(topOperator);
				}
			}
			if (!leftFound){
				throw new UnclosedParenthesisException();
			}
		}
	}

	@Override
	public void checkCorrectSyntax(Token t) throws WrongExpressionException {
		if (Utilities.LEFT_PARENTHESIS.equals(this.getId())){
			if (t.isOperator()){
				throw new WrongExpressionException(this, t);
			}
		}
	}

	@Override
	public Boolean isOperator() {
		return Boolean.FALSE;
	}

	@Override
	public Boolean isNumber() {
		return Boolean.FALSE;
	}

}
